<template>
  <div class="h-full flex flex-col">
    <div class="h-full flex flex-col">
      <a-card>
        <div slot="title">
          <a-space>
            <div class="ty"></div>
            {{ $t("menu.account.settings") }}
          </a-space>
          <div class="flex justify-end items-center">
            <div style="width: 220px;">
              <a-popconfirm :cancel-text="$t('user.email.required11')" :ok-text="$t('user.verification-code.required1166')"
                :title="$t('user.verification-code.required11156611057722511')
                  " @confirm="() => goUpdate()">
                <a-button :size="30" class="hover:bg-[#3F8CFF] hover:bg-opacity-5 shadow">{{
                  $t("app.update") }}</a-button>
              </a-popconfirm>
            </div>
            <!-- 新增/导出 -->
            <a-dropdown style="right: 0; position: absolute; margin-right: 25px">
              <a-menu slot="overlay">
                <a-menu-item key="1" @click="create('add')">
                  {{ $t("menu.result.success") }}
                </a-menu-item>
                <a-menu-item
                  key="2"
                  @click="start"
                  v-if="userroleid.indexOf('35') != -1"
                  :disabled="!hasSelected"
                >
                  {{ $t("user.password.strength.low222333") }}
                </a-menu-item>
              </a-menu>
              <a-button type="primary">
                <a-icon type="bars" />
                {{ $t("di.menus") }}
                <a-icon type="down" />
              </a-button>
            </a-dropdown>
          </div>
        </div>
        <!-- 主列表 -->
        <a-table
          ref="table"
          size="middle"
          class="h-full overflow-x-auto"
          :dataSource="listData"
          :pagination="false"
          :scroll="{ x: 1700, y: 3000 }"
          @change="tableChange"
          :loading="listLoading"
          :rowKey="(record) => record.Id"
        >
          <!--  APPID  -->
          <a-table-column
            key="AppId"
            data-index="AppId"
            width="100px"
            style="position: relative"
            @filterDropdownVisibleChange="
              (e) => {
                if (e) this.setValus(1);
              }
            "
          >
            <!--  标题  -->
            <span slot="title" class="min-w-90p">DGP ID</span>
            <!--  筛选+搜索功能  -->
            <span
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"

            >
              <table-select
                ref="tableselect1"
                :filter-data="filterData"
                @searchCommit="searchQuery"
                @searchFilter="searchQueryFilter"
                @searchClose="confirm"
                @searchClean="tableCleanJobs"
                :scroll="handleScroll"
              />
            </span>
          </a-table-column>
          <!-- APP名称 -->
          <a-table-column
            key="AppName"
            data-index="AppName"
            width="250px"
            @filterDropdownVisibleChange="(e) => (this.setValusKey = 2)"
          >
            <span slot="title" class="min-w-90p">{{
              $t("menu.list.search-list.projects")
            }}</span>
            <!--  搜索功能  -->
            <span
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"
            >
              <table-select
                ref="tableselect2"
                :filter-data="[]"
                @searchCommit="searchQuery"
                @searchClose="confirm"
                @searchClean="tableCleanJobs"
              />
            </span>
            <!--  内容  -->
            <template slot-scope="text, record">
              <span v-if="text == ''" class="blocks"> N/A </span>
              <span v-else>
                {{ record.AppName }}
              </span>
            </template>
          </a-table-column>
          <!-- APP联系人 -->
          <a-table-column
            key="AppOwner"
            data-index="AppOwner"
            width="150px"
            @filterDropdownVisibleChange="
              (e) => {
                if (e) this.setValus(3);
              }
            "
          >
            <!-- 标题 -->
            <span slot="title" class="min-w-90p">{{ $t("menu.profile") }}</span>
            <!--  筛选  -->
            <span
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"
            >
              <table-select
                ref="tableselect3"
                :single-search="false"
                :filter-data="filterData"
                @searchFilter="searchQueryFilter"
                @searchClose="confirm"
                @searchClean="tableCleanJobs"
              />
            </span>
            <!--  内容  -->
            <template slot-scope="text, record">
              <span v-if="text == ''" class="blocks"> N/A </span>
              <span v-else>
                {{ record.AppOwner }}
              </span>
            </template>
          </a-table-column>
          <!-- APP所在部门 -->
          <a-table-column
            key="AppDepartment"
            data-index="AppDepartment"
            width="110px"
            @filterDropdownVisibleChange="
              (e) => {
                if (e) this.setValus(4);
              }
            "
          >
            <!-- 标题 -->
            <span slot="title">{{ $t("menu.profile.advanced") }}</span>
            <!--  筛选  -->
            <span
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"
            >
              <table-select
                ref="tableselect4"
                :single-search="false"
                :filter-data="filterData"
                @searchFilter="searchQueryFilter"
                @searchClose="confirm"
                @searchClean="tableCleanJobs"
                :scroll="handleScroll"
              />
            </span>
            <!--  内容  -->
            <template slot-scope="text, record">
              <span v-if="text == ''" class="blocks"> N/A </span>
              <span v-else>
                {{ record.AppDepartment }}
              </span>
            </template>
          </a-table-column>
          <!-- BMWAPPID -->
          <a-table-column
            key="BmwAppId"
            data-index="BmwAppId"
            width="90px"
            @filterDropdownVisibleChange="
              (e) => {
                if (e) this.setValus(5);
              }
            "
          >
            <!-- 标题 -->
            <span slot="title">enterprise APP ID</span>
            <!--  筛选+搜索功能  -->
            <span
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"
            >
              <table-select
                ref="tableselect5"
                :filter-data="filterData"
                @searchCommit="searchQuery"
                @searchFilter="searchQueryFilter"
                @searchClose="confirm"
                @searchClean="tableCleanJobs"
                :scroll="handleScroll"
              />
            </span>
            <!--  内容  -->
            <template slot-scope="text, record">
              <span v-if="text == ''" class="blocks"> N/A </span>
              <span v-else>
                {{ record.BmwAppId }}
              </span>
            </template>
          </a-table-column>
          <!-- BBA APPID -->
          <a-table-column
            key="BbaAppId"
            data-index="BbaAppId"
            width="100px"
            @filterDropdownVisibleChange="
              (e) => {
                if (e) this.setValus(6);
              }
            "
          >
            <span slot="title">Department APP ID</span>
            <!--  筛选+搜索功能  -->
            <span
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"
            >
              <table-select
                ref="tableselect6"
                :filter-data="filterData"
                @searchCommit="searchQuery"
                @searchFilter="searchQueryFilter"
                @searchClose="confirm"
                @searchClean="tableCleanJobs"
                :scroll="handleScroll"
              />
            </span>
            <!--  内容  -->
            <template slot-scope="text, record">
              <span v-if="text == ''" class="blocks"> N/A </span>
              <span v-else>
                {{ record.BbaAppId }}
              </span>
            </template>
          </a-table-column>
          <!-- FeatherId -->
          <a-table-column
            key="FeatherId"
            data-index="FeatherId"
            width="100px"
            @filterDropdownVisibleChange="
              (e) => {
                if (e) this.setValus(7);
              }
            "
          >
            <span slot="title">Feature ID</span>
            <!--  筛选+搜索功能  -->
            <span
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"
            >
              <table-select
                ref="tableselect7"
                :filter-data="filterData"
                @searchCommit="searchQuery"
                @searchFilter="searchQueryFilter"
                @searchClose="confirm"
                @searchClean="tableCleanJobs"
                :scroll="handleScroll"
              />
            </span>
            <!--  内容  -->
            <template slot-scope="text, record">
              <span v-if="text == ''" class="blocks"> N/A </span>
              <span v-else>
                {{ record.FeatherId }}
              </span>
            </template>
          </a-table-column>
          <!-- 创建时间 -->
          <a-table-column
            key="AppCreatetime"
            data-index="AppCreatetime"
            width="170px"
            @filterDropdownVisibleChange="
              (e) => {
                if (e) this.setValus(8);
              }
            "
          >
            <!-- 标题 -->
            <span slot="title">{{ $t("menu.result.fail") }}</span>
            <!--  筛选  -->
            <span
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"
            >
              <table-select
                ref="tableselect8"
                :single-search="false"
                :filter-data="filterData"
                @searchFilter="searchQueryFilter"
                @searchClose="confirm"
                @searchClean="tableCleanJobs"
                :scroll="handleScroll"
              />
            </span>
            <!--  内容  -->
            <template slot-scope="text, record">
              <span v-if="text == ''" class="blocks"> N/A </span>
              <span v-else>
                {{ record.AppCreatetime }}
              </span>
            </template>
          </a-table-column>
          <!-- 更新时间 -->
          <a-table-column
            key="AppUpdatetime"
            data-index="AppUpdatetime"
            width="170px"
            @filterDropdownVisibleChange="
              (e) => {
                if (e) this.setValus(9);
              }
            "
          >
            <!-- 标题 -->
            <span slot="title">{{ $t("menu.exception") }}</span>
            <!--  筛选  -->
            <span
              slot="filterDropdown"
              slot-scope="{
                setSelectedKeys,
                selectedKeys,
                confirm,
                clearFilters,
                column,
              }"
            >
              <table-select
                ref="tableselect9"
                :single-search="false"
                :filter-data="filterData"
                @searchFilter="searchQueryFilter"
                @searchClose="confirm"
                @searchClean="tableCleanJobs"
                :scroll="handleScroll"
              />
            </span>
            <!--  内容  -->
            <template slot-scope="text, record">
              <span v-if="text == ''" class="blocks"> N/A </span>
              <span v-else>
                {{ record.AppUpdatetime }}
              </span>
            </template>
          </a-table-column>
          <!-- 备注 -->
          <a-table-column
            key="AppRemarks"
            data-index="AppRemarks"
          >
            <span slot="title">{{
              $t("user.verification-code.required1115661812345")
            }}</span>
            <!--  内容  -->
            <template slot-scope="text, record">
              <span v-if="text == ''" class="blocks"> N/A </span>
              <span v-else>
                {{ record.AppRemarks }}
              </span>
            </template>
          </a-table-column>
          <!-- 操作 -->
          <a-table-column
            key="action"
            :title="$t('menu.exception.not-find')"
            width="80px"
            fixed="right"
          >
            <template slot-scope="text, record">
              <span>
                <a-dropdown>
                  <a-button type="link">
                    <a-icon type="more" />
                  </a-button>
                  <template #overlay>
                    <a-menu>
                      <!-- 审阅按钮 -->
                      <a-menu-item @click="showReview(record.Id)">
                        <a-button type="link">{{
                          $t("user.verification-code.required1115661105718")
                        }}</a-button>
                      </a-menu-item>
                      <!-- 修改按钮 -->
                      <a-menu-item
                        v-if="
                          record.AppCreateUserId == userdata.YtId ||
                          userdata.appid
                        "
                        @click="edit(record, 'updata')"
                      >
                        <a-button type="link">{{
                          $t("user.verification-code.required111566147")
                        }}</a-button>
                      </a-menu-item>
                      <!-- 删除按钮 -->
                      <a-menu-item
                        v-if="
                          record.AppCreateUserId == userdata.YtId ||
                          userdata.appid
                        "
                      >
                        <a-popconfirm
                          :title="
                            $t('user.verification-code.required111566110577225')
                          "
                          :ok-text="$t('user.verification-code.required1166')"
                          :cancel-text="$t('user.email.required11')"
                          @confirm="() => del(record.Id)"
                        >
                          <a-button
                            type="link"
                            size="small"
                            style="
                              margin-left: 9px;
                              width: 100%;
                              text-align: left;
                            "
                            >{{ $t("menu.exception.trigger") }}</a-button
                          >
                        </a-popconfirm>
                      </a-menu-item>
                      <!-- 跳转到数据发现 -->
                      <a-menu-item
                        v-if="
                          record.DiscoverState == 1 &&
                          record.AppCreateUserId == userdata.YtId
                        "
                        @click="toFinds(record.Id)"
                      >
                        <a-button type="link">{{
                          $t("menu.account")
                        }}</a-button>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </span>
            </template>
          </a-table-column>
        </a-table>
        <!-- 分页 -->
        <a-pagination
          size="small"
          v-model="pagination.current"
          :total="pagination.total"
          hideOnSinglePage
          :pageSize.sync="pagination.pageSize"
          @change="getList"
        />
      </a-card>
    </div>
    <!-- 抽屉组件  ref绑定save  succeed绑定初始化的 init事件  -->
    <!-- <save ref="save" @succeed="init"/> -->
    <!-- <riskReview ref="riskReview" @succeed="init" :editId="editId"></riskReview> -->
    <add-app ref="addapp" @getList="getList" />
    <div class="big-box" v-if="ifLoading">
      <a-spin />
    </div>
  </div>
</template>

<script>
import tableSelect from "@/components/tableSelect/tableSelect.vue";
// 引入save组件
// import Save from './components/save.vue'
import { appGroup, appIdDelete, appIdDetailList, appIdList,appUpdate } from "@/api/appid";
import { userQuery } from "@/api/common/form";
// import riskReview from './components/saveView.vue'
import axios from "axios";
import moment from "moment";
import { getUserInfo } from "@/api/index";
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import addApp from "@/components/componentLibrary/addapp.vue";

export default {
  name: "appid",
  // 挂载 save组件
  components: { tableSelect, addApp },
  data() {
    return {
      userroleid: "",
      setValusKey: "",
      inputValue: "",
      filterData: [],
      /**table数据 */
      listData: [],
      userList: [],
      appList: [],
      //获取用户的ID 判断是否可以编辑
      userdata: {},
      //编辑是判断是否可以编辑
      bianjiuserId: "",
      //编辑是否出现
      banjiFlag: false,
      //点编辑向子组件传所选项ID
      editId: 0,
      selectedRowKeys: [],
      //控制导出表格
      hasSelected: true,
      userCreateID: "",
      // table的loading 状态
      listLoading: false,
      // 搜索from的对象 直接使用queryForm.AppId赋值
      queryForm: {
        AppId: undefined,
        AppName: undefined,
        AppOwner: undefined,
        FeatherId: undefined,
        BbaAppId: undefined,
        BmwAppId: undefined,
        AppDepartment: undefined,
      },
      // 分页参数
      pagination: {
        current: 1, //当前页
        pageSize: 10, //每页条数
        total: 0, //总条数
        showQuickJumper: true,
        hideOnSinglePage: true,
        showTotal: (total) =>
          this.$t(
            "user.verification-code.required111566110577216",
            { total },
            "user.verification-code.required111566110577217"
          ),
      },
      // 可以选中
      kvMap: [
        "",
        "AppId",
        "",
        "AppOwner",
        "AppDepartment",
        "BmwAppId",
        "BbaAppId",
        "FeatherId",
        "AppCreatetime",
        "AppUpdatetime",
      ],
      okyMap: [
        "",
        "AppIds",
        "AppNames",
        "",
        "",
        "BmwAppIds",
        "BbaAppIds",
        "FeatherIds",
      ],
      ifLoading: false,

			pageNo: 1, // 当前加载的页数
			pageSize: 30, // 每页加载的数据个数
			datasourceCount: 0, // 服务器返回的响应信息
			fetchUserContent: '',// 存储搜索的关键词
      handleScroll: this.scroll,
      typeId: 1,
    };
  },
  created() {
    this.init();
    this.getDatasourceList()
  },
  methods: {
    async getDatasourceList() {
      this.listLoading = true
      try {
        const { data:data,total } = await appGroup({ Condition: this.typeId,page: this.pageNo, pageSize: this.pageSize });
        if (this.filterData.length < this.datasourceCount) {
          this.filterData = this.filterData.concat(data)
        }else {
          this.filterData = data;
        }
        this.datasourceCount = total
      } catch (error) {
        console.error(error)
      } finally {
        this.listLoading = false
      }
    },
      async scroll(e) {
        const target = e.target
        if (!target) return 
        if (
          ((Math.ceil(target.scrollTop) + target.offsetHeight) >= (target.scrollHeight * 1 - 10))
          &&
          (this.pageNo * this.pageSize < this.datasourceCount)
          &&
          this.listLoading === false
        ) {
          this.pageNo += 1
          this.getDatasourceList()
        }
       
      },
    // 查询Filter逻辑
    async setValus(typeId) {
      this.typeId = typeId;
      this.pageNo = 1
      this.listLoading = true;
      try {
        // 调用查询列表
        const { data } = await appGroup({ Condition: typeId,page: this.pageNo, pageSize: this.pageSize });
        // 赋值类型，用于筛选、搜索的直接调用
        this.setValusKey = typeId;
        // 赋值筛选的列表，直接赋值
        this.filterData = data;

      } catch (error) {
        // 报错信息
        this.$message.error(error);
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false;
      }
    },
   
    /**
     * 清空查询数据，并且执行查询
     * @returns {Promise<void>}
     */
    async tableCleanJobs(type) {
      this.pagination.page = 1;
      if (type === "part") {
        this.queryForm[this.kvMap[this.setValusKey]] = undefined;
        this.queryForm[this.okyMap[this.setValusKey]] = undefined;
      } else {
        this.queryForm = {};
        for (let i = 1; i <= 9; i++) {
          let dom = this.$refs[`tableselect${i}`];
          if (dom) {
            dom.inputValue = "";
            dom.inputCheckValue = [];
          }
        }
      }
      this.inputValue = "";
      await this.getList();
    },
    /**
     * 列表筛选查询
     * @param e 筛选的值
     * @param original 筛选的初值
     * @returns {Promise<void>}
     */
    async searchQueryFilter(e, original) {
      this.queryForm[this.okyMap[this.setValusKey]] = undefined;
      this.queryForm = {
        ...this.queryForm,
        [this.kvMap[this.setValusKey]]:
          this.setValusKey === 3 ? original.join("#@%$") : e,
      };
      await this.getList("filter");
    },
    /**
     * 列表搜索查询
     * @param e 搜索的值
     * @returns {Promise<void>}
     */
    async searchQuery(e) {
      this.queryForm[this.kvMap[this.setValusKey]] = undefined;
      this.queryForm = {
        ...this.queryForm,
        [this.okyMap[this.setValusKey]]: e,
      };
      await this.getList("filter");
    },
    //导出表格
    async start() {
      let id = this.selectedRowKeys.join(",");
      // let token1 = this.$store.state.user.token;
      try {
        this.ifLoading = true;
        const data = await axios({
          url: `${process.env.VUE_APP_BASE_API}/v1/appid/export`,
          method: "post",
          params: { id: id },
          headers: {
            // 'Token': token1,
            token: storage.get(ACCESS_TOKEN),
            tokens: storage.get("bmwToken") || "",
          },
          // headers: {
          //   'Token': token1, // yourToken为您保存的token
          // },
          responseType: "arraybuffer",
        });
        this.ifLoading = false;
        if (data.status == 200) {
          const url = window.URL.createObjectURL(
            new Blob([data.data], {
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            })
          );
          const link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", `平台数据${moment().format("L")}.xls`);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          this.$message.error(
            this.$t("user.verification-code.required111566110577327")
          );
        }
      } catch (error) {
        this.$message.error(error);
        console.log(error);
      }
    },
   
    tableChange(e, searchInputs, pagination) {
      // this.pagination = pagination
      var parames = Object.keys(searchInputs);
      for (var i = 0; i < parames.length; i++) {
        searchInputs[parames[i]] = searchInputs[parames[i]].join();
      }
      this.queryForm = { ...searchInputs };
      this.getList("filter");
    },
    /**
     * 初始化数据
     * @returns {Promise<void>}
     */
    async init() {
      //获取用户信息
      const { data } = await getUserInfo();
      this.userroleid = data.role;
      this.userdata = data;
      this.pagination.current = 1;
      await this.getList();
      // 获取用户列表下拉
      const { data: userList } = await userQuery(1);
      this.userList = userList;
    },
    async getList(state) {
      this.listLoading = true;
      const { current, pageSize } = this.pagination;
      try {
        if (state == "filter") {
          // 调用查询列表
          const { data } = await appIdList({
            ...{ page: 1, pageSize: 10 },
            ...this.queryForm,
          });
          //获取App所属部门下拉
          const { data: appList } = await userQuery(2);
          this.appList = appList;
          // 解构赋值
          const { Page, PageSize, Total, Lists } = data;
          // 给table赋值
          this.listData = Lists || [];
          // 给分页数据赋值
          this.pagination = {
            current: Page,
            pageSize: PageSize,
            total: Total,
          };
        } else {
          // 调用查询列表
          const { data } = await appIdList({
            ...{ page: current, pageSize },
            ...this.queryForm,
          });
          //获取App所属部门下拉
          const { data: appList } = await userQuery(2);
          this.appList = appList;
          // 解构赋值
          const { Page, PageSize, Total, Lists } = data;
          // 给table赋值
          this.listData = Lists || [];
          // 给分页数据赋值
          this.pagination = {
            current: Page,
            pageSize: PageSize,
            total: Total,
          };
        }
      } catch (error) {
        console.log(error);
        // 报错信息
        this.$message.error(error);
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false;
      }
    },
    /**
     * 创建 通用的
     */
    create() {
      // 使用ref绑定的组件使用 this.$refs.save.open() 调用组件中的open方法
      // 创建不需要传递参数
      this.$refs.addapp.open(undefined, undefined, false);
    },
    /**
     * 修改 通用的
     * @param {*}
     */
    edit(data, record) {
      // 使用ref绑定的组件使用 this.$refs.save.open() 调用组件中的open方法
      // 修改需要传递参数 1代表是修改 data是表格里面传过来的参数
      this.$refs.addapp.open(1, data);
    },
    /**
     * 查看 通用的
     */
    async showReview(id) {
      try {
        //回显传值
        const { data } = await appIdDetailList({ Id: id });
        await this.$refs.addapp.open(3, data);
      } catch (error) {
        // 报错信息
        this.$message.error(error);
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false;
      }
    },
    /**
     * 删除 通用的
     * @param {*} key
     */
    async del(id) {
      try {
        // 传过来的id直接请求删除api
        await appIdDelete({ id });
        this.$message.success(
          this.$t("user.verification-code.required111566110577133")
        );
        // 重新初始化列表刷新数据
        await this.init();
      } catch (error) {
        this.$message.error(error);
      } finally {
      }
    },
    toFinds(id) {
      this.$router.push({ path: "/find/detail", query: { id } });
    },
    // update
    async goUpdate() {
      try {
        await appUpdate()
        this.$message.success(this.$t('app.update.Successfully'))

      } catch (error) {
        this.$message.error(this.$t('app.update.Updating'))
      }
    },
  },
};
</script>

<style>
.blocks {
  color: #5076a5;
}
.ant-pagination {
  float: right;
}
.big-box {
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.7);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999999;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
